package com.funeral.api.baidu.map.util;

import com.funeral.api.baidu.map.dto.CoordConvertParam;
import com.funeral.api.baidu.map.dto.Coord;
import com.funeral.exception.CallException;
import com.funeral.util.CommonUtils;
import com.funeral.util.HttpClientUtils;
import org.apache.http.client.methods.HttpGet;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class CoordConvertUtils {
    public static HttpGet getHttpGet(String url, CoordConvertParam param) throws CallException{
        if(param == null){
            throw new CallException("param is blank!");
        }
        Map<String,String> httpParam = new HashMap<String,String>();
        httpParam.put("coords",getQueryString(param.getCoords()));
        httpParam.put("ak",param.getAk());
        httpParam.put("output",param.getOutput());
        httpParam.put("from",String.valueOf(param.getFrom()));
        httpParam.put("to",String.valueOf(param.getTo()));
        httpParam.put("sn",param.getSn());
        String uri = HttpClientUtils.addParamForGET(url,httpParam);
        HttpGet httpGet = new HttpGet(uri);
        return httpGet;
    }

    public static String getQueryString(Collection<Coord> coords){
        if(CommonUtils.isBlank(coords)){
            return null;
        }
        StringBuffer result = new StringBuffer();
        String separator = "";
        for (Coord coord:coords){
            if(coord.getLatitude() == null || coord.getLongitude() == null){
                continue;
            }
            result.append(separator);
            result.append(coord.getLongitude());
            result.append(",");
            result.append(coord.getLatitude());
            separator = ";";
        }
        if(StringUtils.isEmpty(separator)){
            return null;
        }
        return result.toString();
    }

}
